export default class PointerEvent {
  $scroller;
  // 截流函数，时间戳
  #timestamp = 0;
  // 截流函数，时间间隔
  #interval = 50;
  // 当前移动距离
  #moveX = 0;
  // 开始坐标
  #startX = 0;
  // 结束位置
  #endX;
  constructor({ $selector, $scroller, onTimeAxisScroll }) {
    this.$scroller = $scroller;
    this.onTimeAxisScroll = onTimeAxisScroll;
    this.bindEvent($selector);
  }
  /**
   * 对外暴露接口
   *
   * @param arg
   */
  onTimeAxisScroll = (arg) => {}

  /**
   * 鼠标按下，计算开始
   *
   * @param event
   */
  onMouseDown = (event) => {
    event.stopPropagation()
    const $scroller = $(event.target).closest('.time-scroller');
    this.#startX = $scroller.offset().left;
    this.bindMouseMove()
  }

  /**
   * 鼠标移动
   *
   * @param event
   */
  onMouseMove = (event) => {
    if (event.which && event.which !== 3) {
      if (Date.now() - this.#timestamp > this.#interval) {
        // console.log(event.offsetX)
        this.#moveX = event.pageX - this.#startX;
        this.onTimeAxisScroll(this.#moveX);
        this.#timestamp = Date.now();
      }
    } else {
      this.offMouseMove()
    }
  }

  /**
   * 结束移动
   *
   * @param event
   */
  onMouseUp = (event) => {
    this.#moveX = event.pageX - this.#startX;
    this.#endX = event.pageX
    this.onTimeAxisScroll(this.#moveX, event);
    this.#timestamp = 0;
    this.offMouseMove()
  }

  /**
   * 移除事件
   */
  offMouseMove = () => {
    // console.log('offMouseMove')
    $(document)
        .off('mousemove', this.onMouseMove)
    $(document)
        .off('mouseup', this.onMouseUp)
  }

  /**
   * 绑定事件
   */
  bindMouseMove = () => {
    $(document)
        .off('mousemove', this.onMouseMove)
        .on('mousemove', this.onMouseMove)
    $(document)
        .off('mouseup', this.onMouseUp)
        .on('mouseup', this.onMouseUp)
  }

  // 销毁 - 接触事件
  off = () => {
    this.$scroller.off('mousedown', this.onMouseDown);
    this.offMouseMove()
  }

  bindEvent = ($selector) => {
    $selector.off('mousedown', this.onMouseDown);
    $selector.on('mousedown', this.onMouseDown);
  }
}